package palmtop.com.palmtop.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.beardedhen.androidbootstrap.AwesomeTextView;
import com.beardedhen.androidbootstrap.BootstrapEditText;

import net.grandcentrix.tray.AppPreferences;

import org.greenrobot.eventbus.EventBus;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import palmtop.com.palmtop.R;
import palmtop.com.palmtop.event.CluelistSyncEvent;
import palmtop.com.palmtop.event.MainSyncEvent;
import palmtop.com.palmtop.util.Config;
import palmtop.com.palmtop.util.FuncUtil;
import palmtop.com.palmtop.util.MusicPlayer;
import palmtop.com.palmtop.util.NetUtil;
import palmtop.com.palmtop.util.PlaybackDialogFragment;
import palmtop.com.palmtop.util.RecordAudioDialogFragment;
import palmtop.com.palmtop.util.RecordingItem;
import palmtop.com.palmtop.util.ToastUtil;

public class AddClueActivity extends BaseActivity implements GeocodeSearch.OnGeocodeSearchListener{

    @BindView(R.id.mtitle)
    TextView mtitle;
    @BindView(R.id.reportman)
    AwesomeTextView reportman;
    @BindView(R.id.position)
    BootstrapEditText position;
    @BindView(R.id.selectmapBtn)
    Button selectmapBtn;
    @BindView(R.id.longitude)
    BootstrapEditText longitude;
    @BindView(R.id.latitude)
    BootstrapEditText latitude;
    /*@BindView(R.id.cluetypename)
    BootstrapEditText cluetypename;*/
    /*@BindView(R.id.addtime)
    BootstrapEditText addtime;*/
    @BindView(R.id.cluecontent)
    BootstrapEditText cluecontent;
    @BindView(R.id.footBtn)
    Button footBtn;
    @BindView(R.id.zphoto1)
    ImageButton zphoto1;
    @BindView(R.id.zphoto2)
    ImageButton zphoto2;
    @BindView(R.id.zphoto3)
    ImageButton zphoto3;
    @BindView(R.id.zphoto4)
    ImageButton zphoto4;
    String userid = "";
    String name = "";
    String ssgrid = "";
    String gridname = "";
    @BindView(R.id.start)
    Button start;
    /*@BindView(R.id.stop)
    Button stop;*/
    @BindView(R.id.play)
    Button play;
    private ArrayList<String> urlarr;
    private String filePathstart1, filePathstart2, filePathstart3, filePathstart4;
    private File cameraFilestart1, cameraFilestart2, cameraFilestart3, cameraFilestart4;
    private String filePathstartPress1, filePathstartPress2, filePathstartPress3, filePathstartPress4;

    private MediaRecorder mMediaRecorder;
    private File recAudioFile;
    private MusicPlayer mPlayer;

    public AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption mLocationOption = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_clue, Config.toptitle, 1);
        MyApplication app = (MyApplication) getApplication();
        app.addActivityList(AddClueActivity.this);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        mtitle.setText("线索上报");
        /*stop.setEnabled(false);
        play.setEnabled(false);*/
//        mPermissionsChecker = new PermissionsChecker(this);
        recAudioFile = new File(Environment.getExternalStorageDirectory() + "/newfiles_" + System.currentTimeMillis() + ".mp3");
        urlarr = new ArrayList<String>();
//        sharedPreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
        AppPreferences appPreferences = new AppPreferences(AddClueActivity.this);
        userid = appPreferences.getString("userid", "");
        name = appPreferences.getString("name", "");
        ssgrid = appPreferences.getString("ssgrid", "");
        gridname = appPreferences.getString("gridname", "");
        reportman.setText(name);
        getGpsInfo();
    }
    private void getGpsInfo() {
        mLocationClient = new AMapLocationClient(getApplicationContext());
        mLocationClient.setLocationListener(mLocationListener);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setNeedAddress(true);
        mLocationOption.setOnceLocation(true);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
        // app = (MyApplication) getApplication();
//        latgps = latgpsnew + "";
//        latgps = longpsnew + "";


    }

    @OnClick(R.id.selectmapBtn)
    public void onSelectmapBtnClicked() {
        startActivityForResult(new Intent(AddClueActivity.this, SelectPositionActivity.class), 5);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            mPhotoPopwindow1.dismiss();
            if (resultCode == RESULT_OK) {
                if (cameraFilestart1 != null) {
                    Bitmap bitmap = null;
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 7;//直接设置它的压缩率，表示1/2
                    filePathstartPress1 = Environment.getExternalStorageDirectory() + "/newfiles_" + System.currentTimeMillis() + ".jpg";
                    FileOutputStream fos = null;
                    try {
                        bitmap = BitmapFactory.decodeFile(filePathstart1, options);
                        fos = new FileOutputStream(filePathstartPress1);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                        fos.flush();
                        fos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if (bitmap != null) {
                        urlarr.add(filePathstartPress1);
                        zphoto1.setImageBitmap(bitmap);
                        zphoto1.requestFocus();
                        zphoto1.setScaleType(ImageView.ScaleType.FIT_XY);

                        zphoto1.setFocusable(true);
                        zphoto1.setFocusableInTouchMode(true);
                        zphoto1.requestFocus();
                        zphoto1.requestFocusFromTouch();
                        FuncUtil.clickShowBigPic(filePathstartPress1, zphoto1, AddClueActivity.this);
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "内存不足,请重新拍摄!", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
        }


        if (requestCode == 11) {
            mPhotoPopwindow1.dismiss();
            if (resultCode == RESULT_OK) {
                if (Build.VERSION.SDK_INT >= 19) {
                    handleImageOnKitKat1(data);
                } else {
                    handleImageBeforeKitKat1(data);
                }

                Bitmap bitmap = null;
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 7;//直接设置它的压缩率，表示1/2
                filePathstartPress1 = Environment.getExternalStorageDirectory() + "/newfiles_" + System.currentTimeMillis() + ".jpg";
                FileOutputStream fos = null;
                try {
                    bitmap = BitmapFactory.decodeFile(filePathstart1, options);
                    fos = new FileOutputStream(filePathstartPress1);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    fos.flush();
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (bitmap != null) {
                    urlarr.add(filePathstartPress1);
                    zphoto1.setImageBitmap(bitmap);
                    zphoto1.requestFocus();
                    zphoto1.setScaleType(ImageView.ScaleType.FIT_XY);

                    zphoto1.setFocusable(true);
                    zphoto1.setFocusableInTouchMode(true);
                    zphoto1.requestFocus();
                    zphoto1.requestFocusFromTouch();
                    FuncUtil.clickShowBigPic(filePathstartPress1, zphoto1, AddClueActivity.this);
                }
            }
        }

//=====================222===========================
        if (requestCode == 2) {
            mPhotoPopwindow2.dismiss();
            if (resultCode == RESULT_OK) {
                if (cameraFilestart2 != null) {
                    Bitmap bitmap = null;
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 7;//直接设置它的压缩率，表示1/2
                    filePathstartPress2 = Environment.getExternalStorageDirectory() + "/newfiles_" + System.currentTimeMillis() + ".jpg";
                    FileOutputStream fos = null;
                    try {
                        bitmap = BitmapFactory.decodeFile(filePathstart2, options);
                        fos = new FileOutputStream(filePathstartPress2);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                        fos.flush();
                        fos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if (bitmap != null) {
                        urlarr.add(filePathstartPress2);
                        zphoto2.setImageBitmap(bitmap);
                        zphoto2.requestFocus();
                        zphoto2.setScaleType(ImageView.ScaleType.FIT_XY);

                        zphoto2.setFocusable(true);
                        zphoto2.setFocusableInTouchMode(true);
                        zphoto2.requestFocus();
                        zphoto2.requestFocusFromTouch();
                        FuncUtil.clickShowBigPic(filePathstartPress2, zphoto2, AddClueActivity.this);
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "内存不足,请重新拍摄!", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
        }

        if (requestCode == 12) {
            mPhotoPopwindow2.dismiss();
            if (resultCode == RESULT_OK) {
                if (Build.VERSION.SDK_INT >= 19) {
                    handleImageOnKitKat2(data);
                } else {
                    handleImageBeforeKitKat2(data);
                }

                Bitmap bitmap = null;
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 7;//直接设置它的压缩率，表示1/2
                filePathstartPress2 = Environment.getExternalStorageDirectory() + "/newfiles_" + System.currentTimeMillis() + ".jpg";
                FileOutputStream fos = null;
                try {
                    bitmap = BitmapFactory.decodeFile(filePathstart2, options);
                    fos = new FileOutputStream(filePathstartPress2);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    fos.flush();
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (bitmap != null) {
                    urlarr.add(filePathstartPress2);
                    zphoto2.setImageBitmap(bitmap);
                    zphoto2.requestFocus();
                    zphoto2.setScaleType(ImageView.ScaleType.FIT_XY);

                    zphoto2.setFocusable(true);
                    zphoto2.setFocusableInTouchMode(true);
                    zphoto2.requestFocus();
                    zphoto2.requestFocusFromTouch();
                    FuncUtil.clickShowBigPic(filePathstartPress2, zphoto2, AddClueActivity.this);
                }
            }
        }
//======================================================
        if (requestCode == 3) {
            mPhotoPopwindow3.dismiss();
            if (resultCode == RESULT_OK) {
                if (cameraFilestart3 != null) {
                    Bitmap bitmap = null;
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 7;//直接设置它的压缩率，表示1/2
                    filePathstartPress3 = Environment.getExternalStorageDirectory() + "/newfiles_" + System.currentTimeMillis() + ".jpg";
                    FileOutputStream fos = null;
                    try {
                        bitmap = BitmapFactory.decodeFile(filePathstart3, options);
                        fos = new FileOutputStream(filePathstartPress3);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                        fos.flush();
                        fos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if (bitmap != null) {
                        urlarr.add(filePathstartPress3);
                        zphoto3.setImageBitmap(bitmap);
                        zphoto3.requestFocus();
                        zphoto3.setScaleType(ImageView.ScaleType.FIT_XY);

                        zphoto3.setFocusable(true);
                        zphoto3.setFocusableInTouchMode(true);
                        zphoto3.requestFocus();
                        zphoto3.requestFocusFromTouch();
                        FuncUtil.clickShowBigPic(filePathstartPress3, zphoto3, AddClueActivity.this);
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "内存不足,请重新拍摄!", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
        }

        if (requestCode == 13) {
            mPhotoPopwindow3.dismiss();
            if (resultCode == RESULT_OK) {
                if (Build.VERSION.SDK_INT >= 19) {
                    handleImageOnKitKat3(data);
                } else {
                    handleImageBeforeKitKat3(data);
                }

                Bitmap bitmap = null;
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 7;//直接设置它的压缩率，表示1/2
                filePathstartPress3 = Environment.getExternalStorageDirectory() + "/newfiles_" + System.currentTimeMillis() + ".jpg";
                FileOutputStream fos = null;
                try {
                    bitmap = BitmapFactory.decodeFile(filePathstart3, options);
                    fos = new FileOutputStream(filePathstartPress3);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    fos.flush();
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (bitmap != null) {
                    urlarr.add(filePathstartPress3);
                    zphoto3.setImageBitmap(bitmap);
                    zphoto3.requestFocus();
                    zphoto3.setScaleType(ImageView.ScaleType.FIT_XY);

                    zphoto3.setFocusable(true);
                    zphoto3.setFocusableInTouchMode(true);
                    zphoto3.requestFocus();
                    zphoto3.requestFocusFromTouch();
                    FuncUtil.clickShowBigPic(filePathstartPress3, zphoto3, AddClueActivity.this);
                }
            }
        }
//=====================================================================
        if (requestCode == 4) {
            mPhotoPopwindow4.dismiss();
            if (resultCode == RESULT_OK) {
                if (cameraFilestart4 != null) {
                    Bitmap bitmap = null;
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 7;//直接设置它的压缩率，表示1/2
                    filePathstartPress4 = Environment.getExternalStorageDirectory() + "/newfiles_" + System.currentTimeMillis() + ".jpg";
                    FileOutputStream fos = null;
                    try {
                        bitmap = BitmapFactory.decodeFile(filePathstart4, options);
                        fos = new FileOutputStream(filePathstartPress4);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                        fos.flush();
                        fos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if (bitmap != null) {
                        urlarr.add(filePathstartPress4);
                        zphoto4.setImageBitmap(bitmap);
                        zphoto4.requestFocus();
                        zphoto4.setScaleType(ImageView.ScaleType.FIT_XY);

                        zphoto4.setFocusable(true);
                        zphoto4.setFocusableInTouchMode(true);
                        zphoto4.requestFocus();
                        zphoto4.requestFocusFromTouch();
                        FuncUtil.clickShowBigPic(filePathstartPress4, zphoto4, AddClueActivity.this);
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "内存不足,请重新拍摄!", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
        }

        if (requestCode == 14) {
            mPhotoPopwindow4.dismiss();
            if (resultCode == RESULT_OK) {
                if (Build.VERSION.SDK_INT >= 19) {
                    handleImageOnKitKat4(data);
                } else {
                    handleImageBeforeKitKat4(data);
                }

                Bitmap bitmap = null;
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 7;//直接设置它的压缩率，表示1/2
                filePathstartPress4 = Environment.getExternalStorageDirectory() + "/newfiles_" + System.currentTimeMillis() + ".jpg";
                FileOutputStream fos = null;
                try {
                    bitmap = BitmapFactory.decodeFile(filePathstart4, options);
                    fos = new FileOutputStream(filePathstartPress4);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    fos.flush();
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (bitmap != null) {
                    urlarr.add(filePathstartPress4);
                    zphoto4.setImageBitmap(bitmap);
                    zphoto4.requestFocus();
                    zphoto4.setScaleType(ImageView.ScaleType.FIT_XY);

                    zphoto4.setFocusable(true);
                    zphoto4.setFocusableInTouchMode(true);
                    zphoto4.requestFocus();
                    zphoto4.requestFocusFromTouch();
                    FuncUtil.clickShowBigPic(filePathstartPress4, zphoto4, AddClueActivity.this);
                }
            }
        }

        if (requestCode == 5) {
            if(data!=null) {
                String address = data.getExtras().getString("address");
                Double  latitude1 = data.getExtras().getDouble("latitude");
                Double longitude1 = data.getExtras().getDouble("longitude");
                position.setText(address);
                if(latitude1==0.0){
                    latitude.setText("");
                }else{
                    latitude.setText(String.valueOf(latitude1));
                }
                if(longitude1==0.0){
                    longitude.setText("");
                }else{
                    longitude.setText(String.valueOf(longitude1));
                }
            }
        }

    }

    @OnClick(R.id.footBtn)
    public void onFootBtnClicked() {
        RequestParams params = new RequestParams(Config.SERVER_URL + "clue/save");
        params.addBodyParameter("reportid", userid);
        params.addBodyParameter("reportman", name);
        params.addBodyParameter("position", String.valueOf(position.getText()));
        params.addBodyParameter("longitude", String.valueOf(longitude.getText()));
        params.addBodyParameter("latitude", String.valueOf(latitude.getText()));
        Date day = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String addtime = df.format(day);
        params.addBodyParameter("addtime", addtime);
        params.addBodyParameter("type", "0");
        params.addBodyParameter("cluecontent", String.valueOf(cluecontent.getText()));
        params.addBodyParameter("unitid", ssgrid);
        params.addBodyParameter("unitname", gridname);

        if (urlarr != null && urlarr.size() > 0) {
            if (urlarr.get(0) != null && !urlarr.get(0).equals("")) {
                params.addBodyParameter("phone1", new File(urlarr.get(0)));
            }
        }
        if (urlarr != null && urlarr.size() > 1) {
            if (urlarr.get(1) != null && !urlarr.get(1).equals("")) {
                params.addBodyParameter("phone2", new File(urlarr.get(1)));
            }
        }
        if (urlarr != null && urlarr.size() > 2) {
            if (urlarr.get(2) != null && !urlarr.get(2).equals("")) {
                params.addBodyParameter("phone3", new File(urlarr.get(2)));
            }
        }
        if (urlarr != null && urlarr.size() > 3) {
            if (urlarr.get(3) != null && !urlarr.get(3).equals("")) {
                params.addBodyParameter("phone4", new File(urlarr.get(3)));
            }
        }


        SharedPreferences sharePreferences = getSharedPreferences("sp_name_audio", MODE_PRIVATE);
        String filePath = sharePreferences.getString("audio_path", "");
        long elpased = sharePreferences.getLong("elpased", 0);

        if(!filePath.equals("")){
            File file = new File(filePath);
            params.addBodyParameter("recordurl1", file);
            params.addBodyParameter("recordlength", String.valueOf(elpased));
            params.setMultipart(true);
            sharePreferences.edit().clear().commit();
        }

        NetUtil.postData(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (result.equals("success")) {

                    FuncUtil.updateno(ssgrid);
                    FuncUtil.updateno("73006b03b7f447bf953d065462e5b1ac");
                    ToastUtil.show(AddClueActivity.this, "提交成功");
                    EventBus.getDefault().post(new CluelistSyncEvent());
                    finish();
                } else {
                    ToastUtil.show(AddClueActivity.this, "提交失败");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
    }

    //==================================================================================================
    public PhotoPopwindow mPhotoPopwindow1;
    public PhotoPopwindow mPhotoPopwindow2;
    public PhotoPopwindow mPhotoPopwindow3;
    public PhotoPopwindow mPhotoPopwindow4;
    private Uri imageUri;//原图保存地址

    private Handler mHandler1 = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 110:
                    takephoto1();
                    break;
                case 111:
                    selectFromAlbum1();
                    break;
                default:
                    break;
            }
        }
    };

    private Handler mHandler2 = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 110:
                    takephoto2();
                    break;
                case 111:
                    selectFromAlbum2();
                    break;
                default:
                    break;
            }
        }
    };

    private Handler mHandler3 = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 110:
                    takephoto3();
                    break;
                case 111:
                    selectFromAlbum3();
                    break;
                default:
                    break;
            }
        }
    };

    private Handler mHandler4 = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 110:
                    takephoto4();
                    break;
                case 111:
                    selectFromAlbum4();
                    break;
                default:
                    break;
            }
        }
    };
    @OnClick(R.id.zphoto1)
    public void onZphoto1Clicked() {
        mPhotoPopwindow1 = new PhotoPopwindow(AddClueActivity.this, mHandler1,this.getWindowManager());
        mPhotoPopwindow1.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        mPhotoPopwindow1.showAtLocation(findViewById(R.id.footBtn),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    public void takephoto1(){
        filePathstart1 = Environment.getExternalStorageDirectory() + "/files_" + System.currentTimeMillis() + ".png";
        cameraFilestart1 = new File(filePathstart1);
        Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        in.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFilestart1));
        startActivityForResult(in, 1);
    }
    /**
     * 从相册选择
     */
    private void selectFromAlbum1() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, 11);
    }

    @TargetApi(19)
    private void handleImageOnKitKat1(Intent data) {
        filePathstart1 = null;
        imageUri = data.getData();
        if (DocumentsContract.isDocumentUri(this, imageUri)) {
            //如果是document类型的uri,则通过document id处理
            String docId = DocumentsContract.getDocumentId(imageUri);
            if ("com.android.providers.media.documents".equals(imageUri.getAuthority())) {
                String id = docId.split(":")[1];//解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                filePathstart1 = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.downloads.documents".equals(imageUri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                filePathstart1 = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            //如果是content类型的Uri，则使用普通方式处理
            filePathstart1 = getImagePath(imageUri, null);
        } else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            //如果是file类型的Uri,直接获取图片路径即可
            filePathstart1 = imageUri.getPath();
            cameraFilestart1 = new File(filePathstart1);
        }
    }

    private void handleImageBeforeKitKat1(Intent intent) {
        imageUri = intent.getData();
        filePathstart1 = getImagePath(imageUri, null);
        cameraFilestart1 = new File(filePathstart1);
    }





    private String getImagePath(Uri uri, String selection) {
        String path = null;
        //通过Uri和selection老获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }




//=================================================================
    @OnClick(R.id.zphoto2)
    public void onZphoto2Clicked() {
        mPhotoPopwindow2 = new PhotoPopwindow(AddClueActivity.this, mHandler2,this.getWindowManager());
        mPhotoPopwindow2.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        mPhotoPopwindow2.showAtLocation(findViewById(R.id.footBtn),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    public void takephoto2(){
        filePathstart2 = Environment.getExternalStorageDirectory() + "/files_" + System.currentTimeMillis() + ".png";
        cameraFilestart2 = new File(filePathstart2);
        Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        in.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFilestart2));
        startActivityForResult(in, 2);
    }
    /**
     * 从相册选择
     */
    private void selectFromAlbum2() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, 12);
    }

    @TargetApi(19)
    private void handleImageOnKitKat2(Intent data) {
        filePathstart2 = null;
        imageUri = data.getData();
        if (DocumentsContract.isDocumentUri(this, imageUri)) {
            //如果是document类型的uri,则通过document id处理
            String docId = DocumentsContract.getDocumentId(imageUri);
            if ("com.android.providers.media.documents".equals(imageUri.getAuthority())) {
                String id = docId.split(":")[1];//解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                filePathstart2 = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.downloads.documents".equals(imageUri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                filePathstart2 = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            //如果是content类型的Uri，则使用普通方式处理
            filePathstart2 = getImagePath(imageUri, null);
        } else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            //如果是file类型的Uri,直接获取图片路径即可
            filePathstart2 = imageUri.getPath();
            cameraFilestart2 = new File(filePathstart2);
        }
    }

    private void handleImageBeforeKitKat2(Intent intent) {
        imageUri = intent.getData();
        filePathstart2 = getImagePath(imageUri, null);
        cameraFilestart2 = new File(filePathstart2);
    }
//===================================================================
    @OnClick(R.id.zphoto3)
    public void onZphoto3Clicked() {
        mPhotoPopwindow3 = new PhotoPopwindow(AddClueActivity.this, mHandler3,this.getWindowManager());
        mPhotoPopwindow3.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        mPhotoPopwindow3.showAtLocation(findViewById(R.id.footBtn),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    public void takephoto3(){
        filePathstart3 = Environment.getExternalStorageDirectory() + "/files_" + System.currentTimeMillis() + ".png";
        cameraFilestart3 = new File(filePathstart3);
        Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        in.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFilestart3));
        startActivityForResult(in, 3);
    }
    /**
     * 从相册选择
     */
    private void selectFromAlbum3() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, 13);
    }

    @TargetApi(19)
    private void handleImageOnKitKat3(Intent data) {
        filePathstart3 = null;
        imageUri = data.getData();
        if (DocumentsContract.isDocumentUri(this, imageUri)) {
            //如果是document类型的uri,则通过document id处理
            String docId = DocumentsContract.getDocumentId(imageUri);
            if ("com.android.providers.media.documents".equals(imageUri.getAuthority())) {
                String id = docId.split(":")[1];//解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                filePathstart3 = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.downloads.documents".equals(imageUri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                filePathstart3 = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            //如果是content类型的Uri，则使用普通方式处理
            filePathstart3 = getImagePath(imageUri, null);
        } else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            //如果是file类型的Uri,直接获取图片路径即可
            filePathstart3 = imageUri.getPath();
            cameraFilestart3 = new File(filePathstart3);
        }
    }

    private void handleImageBeforeKitKat3(Intent intent) {
        imageUri = intent.getData();
        filePathstart3 = getImagePath(imageUri, null);
        cameraFilestart3 = new File(filePathstart3);
    }
//======================================================================
    @OnClick(R.id.zphoto4)
    public void onZphoto4Clicked() {
        mPhotoPopwindow4 = new PhotoPopwindow(AddClueActivity.this, mHandler4,this.getWindowManager());
        mPhotoPopwindow4.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        mPhotoPopwindow4.showAtLocation(findViewById(R.id.footBtn),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    public void takephoto4(){
        filePathstart4 = Environment.getExternalStorageDirectory() + "/files_" + System.currentTimeMillis() + ".png";
        cameraFilestart4 = new File(filePathstart4);
        Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        in.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFilestart4));
        startActivityForResult(in, 3);
    }
    /**
     * 从相册选择
     */
    private void selectFromAlbum4() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, 14);
    }

    @TargetApi(19)
    private void handleImageOnKitKat4(Intent data) {
        filePathstart4 = null;
        imageUri = data.getData();
        if (DocumentsContract.isDocumentUri(this, imageUri)) {
            //如果是document类型的uri,则通过document id处理
            String docId = DocumentsContract.getDocumentId(imageUri);
            if ("com.android.providers.media.documents".equals(imageUri.getAuthority())) {
                String id = docId.split(":")[1];//解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                filePathstart4 = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.downloads.documents".equals(imageUri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                filePathstart4 = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            //如果是content类型的Uri，则使用普通方式处理
            filePathstart4 = getImagePath(imageUri, null);
        } else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            //如果是file类型的Uri,直接获取图片路径即可
            filePathstart4 = imageUri.getPath();
            cameraFilestart4 = new File(filePathstart4);
        }
    }

    private void handleImageBeforeKitKat4(Intent intent) {
        imageUri = intent.getData();
        filePathstart4 = getImagePath(imageUri, null);
        cameraFilestart4 = new File(filePathstart4);
    }

    @OnClick(R.id.start)
    public void onStartClicked() {
        final RecordAudioDialogFragment fragment = RecordAudioDialogFragment.newInstance();
        fragment.show(getSupportFragmentManager(), RecordAudioDialogFragment.class.getSimpleName());
        fragment.setOnCancelListener(new RecordAudioDialogFragment.OnAudioCancelListener() {
            @Override
            public void onCancel() {
                fragment.dismiss();
            }
        });

    }



    @OnClick(R.id.play)
    public void onPlayClicked() {
        RecordingItem recordingItem = new RecordingItem();
        SharedPreferences sharePreferences = getSharedPreferences("sp_name_audio", MODE_PRIVATE);
        final String filePath = sharePreferences.getString("audio_path", "");
        long elpased = sharePreferences.getLong("elpased", 0);
        recordingItem.setFilePath(filePath);
        recordingItem.setLength((int) elpased);
        PlaybackDialogFragment fragmentPlay = PlaybackDialogFragment.newInstance(recordingItem);
        fragmentPlay.show(getSupportFragmentManager(), PlaybackDialogFragment.class.getSimpleName());
        /*mPlayer = new MusicPlayer(AddClueActivity.this);
        mPlayer.playMicFile(recAudioFile);*/
    }

    double latgpsnew;
    double longpsnew;


    //声明定位回调监听器(需要copy)
    public AMapLocationListener mLocationListener = new AMapLocationListener() {

        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    latitude.setText(amapLocation.getLatitude() + "");
                    longitude.setText(amapLocation.getLongitude() + "");
                    latgpsnew = amapLocation.getLatitude();
                    longpsnew = amapLocation.getLongitude();
                    getAddress(latgpsnew, longpsnew);
                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };

    //自动获取地址(需要copy)
    private void getAddress(double lat, double lon) {
        GeocodeSearch geocodeSearch = new GeocodeSearch(this);
        geocodeSearch.setOnGeocodeSearchListener(this);
        if (latgpsnew != 0.0) {
            RegeocodeQuery query = new RegeocodeQuery(new LatLonPoint(lat, lon), 200, GeocodeSearch.AMAP);
            geocodeSearch.getFromLocationAsyn(query);
        }
    }


    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        if (i == 1000) {
            String addresses = regeocodeResult.getRegeocodeAddress().getFormatAddress();
            position.setText(addresses);
        }

    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }
}
